package com.gsit.ocrbatch.services;

import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.gsit.ocrbatch.controller.EmailProcesser;
import com.gsit.ocrbatch.domain.EmailDetail;
import com.gsit.ocrbatch.domain.EmailMessage;
import com.gsit.ocrbatch.domain.Record;
import com.gsit.ocrbatch.utils.EmailType;
import com.gsit.ocrbatch.utils.MessageUtil;

@Repository
public class EmailService {
	
	@PersistenceContext
	private EntityManager entityManager;
	
	@Autowired
	private EmailProcesser emailProcesser;
	
	
	public void sendMailToAll(Record record){
		try {
			List<EmailDetail> emailDetails = entityManager.createNamedQuery("findAllEmailDetails", EmailDetail.class).getResultList();
			if(emailDetails == null || emailDetails.size() ==0) return;
			for (EmailDetail emailDetail : emailDetails) {
				EmailMessage emailMessage = new EmailMessage(); 
				
				Map<String, Object> variables = new Hashtable<>();
				variables.put("messages", MessageUtil.getMessageList(record.getRecordRejects()));
				variables.put("emailDetail", emailDetail);
				emailMessage.setTemplateVariables(variables);
				emailMessage.setEmailBody(MessageUtil.getMessage(record.getRecordRejects()));
				
				emailMessage.addReceipientList(emailDetail.getEmailId());
				
				
				emailMessage.setEmailSubject("Error during QC .....");
				emailMessage.setEmailType(EmailType.HTML);
				emailProcesser.execute( emailMessage);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

}
